<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

interface Note {
  id: number
  title: string
  content: string
  createdAt: Date
  updatedAt: Date
}

interface Props {
  currentNote: Note | null
}

const emit = defineEmits<{
  'new-note': []
}>()

defineProps<Props>()

const isAlwaysOnTop = ref(false)
const isMenuOpen = ref(false)

const formatDate = (date: Date): string => {
  return date.toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 切换窗口置顶
const toggleAlwaysOnTop = async (): Promise<void> => {
  console.log('置顶按钮被点击，当前状态:', isAlwaysOnTop.value)
  try {
    if (window.api) {
      const newState = await window.api.toggleAlwaysOnTop()
      isAlwaysOnTop.value = newState
      console.log('调用toggleAlwaysOnTop成功，新状态:', newState)
    } else {
      console.error('window.api 不可用')
    }
  } catch (error) {
    console.error('切换置顶状态失败:', error)
  }
}

// 关闭菜单
const closeMenu = (): void => {
  isMenuOpen.value = false
}

// 导出笔记功能
const exportNote = (): void => {
  console.log('导出笔记功能')
  closeMenu()
}

// 分享笔记功能
const shareNote = (): void => {
  console.log('分享笔记功能')
  closeMenu()
}

// 复制笔记内容
const copyNote = async (): Promise<void> => {
  console.log('复制笔记内容')
  closeMenu()
}

// 笔记统计信息
const showStats = (): void => {
  console.log('显示笔记统计')
  closeMenu()
}

// 监听置顶状态变化的回调
const handleAlwaysOnTopChanged = (newState: boolean): void => {
  isAlwaysOnTop.value = newState
}

// 点击外部关闭菜单
const handleClickOutside = (event: Event): void => {
  const target = event.target as Element
  if (!target.closest('.menu-container')) {
    closeMenu()
  }
}

const handleNewNote = (): void => {
  console.log('新建笔记按钮被点击')
  emit('new-note')
}

onMounted(async () => {
  try {
    // 获取初始置顶状态
    isAlwaysOnTop.value = await window.api.getAlwaysOnTop()

    // 监听置顶状态变化
    window.api.onAlwaysOnTopChanged(handleAlwaysOnTopChanged)

    // 监听点击外部关闭菜单
    document.addEventListener('click', handleClickOutside)
  } catch (error) {
    console.error('初始化置顶状态失败:', error)
  }
})

onUnmounted(() => {
  // 清理监听器
  window.api.removeAlwaysOnTopListener()
  document.removeEventListener('click', handleClickOutside)
})
</script>

<template>
  <v-app-bar flat color="white" border>
    <!-- 左侧：笔记信息 -->
    <v-app-bar-title>
      <div>
        <div class="text-h6">
          {{ currentNote ? currentNote.title || '无标题' : '选择一个笔记开始编辑' }}
        </div>
        <div v-if="currentNote" class="text-caption text-grey">
          {{ formatDate(currentNote.updatedAt) }}
        </div>
      </div>
    </v-app-bar-title>

    <v-spacer></v-spacer>

    <!-- 右侧：操作按钮 -->
    <div class="d-flex align-center ga-2">
      <!-- 置顶按钮 -->
      <v-btn
        :icon="isAlwaysOnTop ? 'mdi-pin' : 'mdi-pin-outline'"
        :color="isAlwaysOnTop ? 'primary' : 'grey'"
        variant="outlined"
        size="small"
        @click="toggleAlwaysOnTop"
      >
        <v-icon></v-icon>
        <v-tooltip activator="parent" location="bottom">
          {{ isAlwaysOnTop ? '取消置顶' : '窗口置顶' }}
        </v-tooltip>
      </v-btn>

      <!-- 更多操作菜单 -->
      <v-menu v-if="currentNote" v-model="isMenuOpen">
        <template #activator="{ props }">
          <v-btn icon="mdi-dots-vertical" variant="outlined" size="small" v-bind="props"></v-btn>
        </template>

        <v-list density="compact" min-width="200">
          <v-list-item @click="exportNote">
            <template #prepend>
              <v-icon icon="mdi-file-export" size="small"></v-icon>
            </template>
            <v-list-item-title>导出笔记</v-list-item-title>
          </v-list-item>

          <v-list-item @click="copyNote">
            <template #prepend>
              <v-icon icon="mdi-content-copy" size="small"></v-icon>
            </template>
            <v-list-item-title>复制内容</v-list-item-title>
          </v-list-item>

          <v-list-item @click="shareNote">
            <template #prepend>
              <v-icon icon="mdi-share-variant" size="small"></v-icon>
            </template>
            <v-list-item-title>分享笔记</v-list-item-title>
          </v-list-item>

          <v-divider></v-divider>

          <v-list-item @click="showStats">
            <template #prepend>
              <v-icon icon="mdi-chart-line" size="small"></v-icon>
            </template>
            <v-list-item-title>笔记统计</v-list-item-title>
          </v-list-item>
        </v-list>
      </v-menu>

      <!-- 新建笔记按钮 -->
      <v-btn
        color="primary"
        variant="flat"
        size="small"
        prepend-icon="mdi-plus"
        @click="handleNewNote"
      >
        新建
      </v-btn>
    </div>
  </v-app-bar>
</template>

<style scoped>
/* Vuetify提供了大部分样式，这里只需要少量自定义 */
</style>
